<template>
  <div>
    <vm-status v-if="showStatus"
               empty-text="没有龙头企业~"
               :type="isError ? 'error' : 'empty'"></vm-status>

    <scroller v-else
              :show-scrollbar="false">

      <div class="flex-row-wp pt-2">
        <text class="dt">龙头企业:</text>
        <text class="dd">{{servicer.service_name}}</text>
      </div>
      <div class="flex-row-wp">
        <text class="dt">联系人:</text>
        <text class="dd">{{servicer.res_person_name}}({{servicer.res_phone_number}})</text>
      </div>
      <div class="flex-row-wp mb-1">
        <text class="dt">客户地址:</text>
        <text class="dd">{{servicer.address}}</text>
      </div>

      <vm-status v-if="showStoreStatus"
                 empty-text="没有产品~"
                 :type="isStoreError ? 'error' : 'empty'"></vm-status>

      <div v-else>
        <div class="td-row">
          <text class="td-serial text-muted"></text>
          <text class="td-text text-muted">产品</text>
          <text class="td-text text-muted">单价(元/千克)</text>
          <text class="td-text text-muted">均重(千克)</text>
          <text class="td-text text-muted">出库数量</text>
        </div>
        <div class="list-row"
             v-for="(store, index) in stores"
             :key="index"
             @click="toggleSelect(store)">
          <div class="flex-row mb-1">
            <div class="td-serial align-center">
              <text v-if="store.selected"
                    class="icon text-primary td-select-icon">&#xebf1;</text>
              <text v-else
                    class="icon text-muted td-select-icon">&#xebf0;</text>
            </div>
            <div class="flex mr-1">
              <text class="text">{{store.goods_name}}</text>
              <text class="text-sm text-muted">库存: {{store.store_amount}}</text>
              <text class="text-sm text-muted">规格: {{store.spec_name}}</text>
            </div>
            <div class="flex mr-1">
              <input type="number"
                     placeholder="填写单价"
                     v-model="store.inputPrice"
                     class="input"
                     @input="onInputPrice(store)" />
            </div>
            <div class="flex mr-1">
              <input type="number"
                     placeholder="填写均重"
                     v-model="store.inputWeight"
                     class="input"
                     @input="onInputPrice(store)" />
            </div>
            <div class="flex">
              <div v-if="store.isChick">
                <div class="flex-row">
                  <text :class="['input', !store.inputAmount && 'text-muted']"
                        @click="selectHouseAmount(store, index)">{{store.inputAmount || '填写数量'}}</text>
                  <text class="unit-text">{{store.spec_unit}}</text>
                </div>
                <text v-for="(extra, j) in store.extraInfo"
                      :key="j"
                      class="text-mini text-muted text-right">{{extra.house_no}}栋{{extra.chick_amount}}{{store.spec_unit}}</text>
              </div>
              <div v-else
                   class="flex-row">
                <input type="number"
                       placeholder="填写数量"
                       v-model="store.inputAmount"
                       class="input"
                       @input="onInputAmount(store)" />
                <text class="unit-text">{{store.spec_unit}}</text>
              </div>
            </div>
          </div>

          <div class="align-right pb-2"
               style="margin-left: 80px;"
               @click="showRemark(store, index)">
            <text class="icon text-sm text-muted"
                  v-if="!store.remark">&#xe791; 备注</text>
            <text class="text-sm text-muted"
                  v-else>备注: {{store.remark}}</text>
          </div>

        </div>
      </div>

    </scroller>

    <div class="submit-wrap"
         v-if="!showStatus && !showStoreStatus">
      <text class="submit-num">&yen; {{inputAmount}}</text>
      <text class="submit-btn"
            @click="submit">提交出库单</text>
    </div>

    <vm-mask height="400"
             width="560"
             ref="remarkMask"
             :top="200"
             :show-close="true"
             :show.sync="remarkVisible"
             @close="maskClose">
      <textarea class="textarea"
                ref="remarkTextarea"
                v-model="remarkMsg"
                rows="8"
                placeholder="填写备注"></textarea>
      <text class="textarea-btn"
            @click="onRemarkConfirm">确认</text>
    </vm-mask>

    <wxc-popup :show="houseVisible"
               ref="housePopup"
               @wxcPopupOverlayClicked="houseBeforeClose"
               pos="bottom"
               :height="700">
      <text class="p-2 text border-bottom icon">&#xe607; 填写鸡舍的出栏数量</text>
      <div class="p-3 align-center"
           v-if="!selectColumn.length">
        <text class="p-3 text-muted text-center">没有{{selectStore.goods_name}}的入舍信息</text>
        <text class="dismiss-btn"
              @click="hideHousePopup">确定</text>
      </div>

      <div class="flex"
           v-else>
        <div class="td-row">
          <text class="td-serial text-muted text-center">栋号</text>
          <text class="td-text text-muted text-center">日龄</text>
          <text class="td-text text-muted text-center">存栏量</text>
          <text class="td-text text-muted text-center">出栏量</text>
        </div>
        <scroller :show-scrollbar="false">
          <div v-for="(column, index) in selectColumn"
               :key="index">
            <text class="text-mini text-muted p-1 bg-light">{{column.enter_batch_no}}</text>
            <div class="flex-row p-1 align-center"
                 v-for="(house, h) in column.enterHouses"
                 :key="h">
              <text class="td-serial text-center text-muted">{{house.house_no}}栋</text>
              <text class="td-text text-center text-muted">{{house.current_day_age}}</text>
              <text class="td-text text-center text-muted">{{house.current_amount}}</text>
              <div class="flex flex-row">
                <input type="number"
                       placeholder="填写数量"
                       v-model="house.inputAmount"
                       class="input"
                       @input="onHouseInputAmount(house)" />
                <text class="unit-text">{{selectStore.spec_unit}}</text>
              </div>
            </div>
          </div>
        </scroller>
        <div class="flex-row popup-btns">
          <div class="popup-btn-border">
            <div class="flex popup-btn popup-btn-dismiss"
                 @click="hideHousePopup">
              <text class="popup-btn-text">取消</text>
            </div>
            <div class="flex popup-btn popup-btn-confirm"
                 @click="onHouseSubmit">
              <text class="popup-btn-text text-white">确认</text>
            </div>
          </div>
        </div>
      </div>
    </wxc-popup>

  </div>
</template>
<script>
import VmButton from '../../components/vm-button.vue'
import VmStatus from '../../components/vm-status.vue'
import VmMask from '../../components/vm-mask.vue'
import { WxcPopup } from 'weex-ui'
import {
  STORAGE_USER,
  STORAGE_FARM
} from '../../plugins/constant'
import {
  CATEGORY_GOODS,
  CATEGORY_CHICK,
  enumHouseStatus
} from '../../plugins/enumChick'

export default {
  components: { VmButton, VmStatus, VmMask, WxcPopup },
  props: {},
  data: () => ({
    isError: false,
    isStoreError: false,
    farm: {},
    servicer: {},
    stores: [],
    //
    remarkIndex: -1,
    remarkVisible: false,
    remarkMsg: '',
    // 鸡类house选择
    columns: [],
    houseVisible: false,
    selectStore: {},
    selectColumn: []
  }),
  computed: {
    showStatus() {
      return this.isError || !this.servicer.service_id
    },
    showStoreStatus() {
      return !this.showStatus && (this.isStoreError || !this.stores.length)
    },
    inputAmount() {
      return this.stores.reduce((total, item) => {
        // 实际卖鸡，先抽样取均重（可能是几笼），再统计总数量（羽），最后算总价 @唐文峰 2019-07-25
        const price = +item.inputPrice || 0
        const weight = +item.inputWeight || 0
        const amount = +item.inputAmount || 0
        return Math.round((total + price * weight * amount) * 100) / 100
      }, 0) || 0
    }
  },
  watch: {},
  created() {
    this.getFarm()
  },
  methods: {
    getFarm() {
      this.farm = this.$storage.getSync(STORAGE_FARM) || {}
      this.user = this.$storage.getSync(STORAGE_USER) || {}

      if (this.farm.id) {
        this.getServicer()
        this.getStores()
        this.getColumnAndHouse()
      } else {
        this.$notice.toast({ message: '没有鸡场信息' })
        this.$router.setBackParams({ type: 1 })
      }
    },
    getServicer() {
      this.$api.getData({
        server: 'agr_chain',
        table: 'supplier_related_view_for_app',
        params: {
          'supplier_id.eq': this.farm.id
        }
      }).then(res => {
        this.isError = false
        const data = res || []
        if (data.length) {
          this.servicer = data[0]
        }
      }).catch(err => {
        this.isError = true
      })
    },
    getStores() {
      this.$api.getData({
        server: 'agr_chain',
        table: 'goods_store_view',
        params: {
          'own_org_id.eq': this.farm.id,
          'goods_category_id.endlike': CATEGORY_GOODS
        },
        order: {
          store_amount: 'desc'
        }
      }).then(res => {
        this.isStoreError = false
        const data = res || []
        this.stores = data.map(item => {
          item.inputAmount = undefined
          item.inputWeight = undefined
          item.inputPrice = item.price
          item.selected = false
          item.remark = undefined
          item.store_amount = this.$utils.removeDecimalZero(item.store_amount)
          item.isChick = item.goods_category_id && item.goods_category_id.indexOf(CATEGORY_CHICK) > -1
          item.extraInfo = []
          return item
        })
      }).catch(err => {
        this.isStoreError = true
      })
    },
    toggleSelect(row) {
      this.$set(row, 'selected', !row.selected)
    },
    showRemark(store, index) {
      this.remarkIndex = index
      this.remarkMsg = store.remark
      this.remarkVisible = true
      setTimeout(() => {
        const ref = this.$refs.remarkTextarea
        ref && ref.focus()
      }, 30)
    },
    onRemarkConfirm() {
      if (this.remarkIndex > -1 && this.remarkIndex < this.stores.length) {
        this.stores[this.remarkIndex].remark = this.remarkMsg
      }
      this.$refs.remarkMask.hide()
      this.maskClose()
    },
    maskClose() {
      this.$tools.resignKeyboard()
    },
    onInputPrice(row) {
      this.$set(row, 'selected', !!row.inputPrice || !!row.inputWeight)
    },
    onInputAmount(row) {
      if (row.inputAmount) {
        const store = +row.store_amount || 0
        // if (+row.inputAmount > store) {
        //   this.$notice.toast({ message: '库存不足' })
        //   this.$set(row, 'inputAmount', store)
        // }
        this.$set(row, 'selected', true)
      } else {
        this.$set(row, 'selected', false)
      }
    },
    // 获取当前入栏及各鸡舍信息
    getColumnAndHouse() {
      this.$api.getData({
        server: 'agr_chain',
        table: 'chick_column_view',
        params: {
          'supplier_id.eq': this.farm.id,
          'column_status.eq': 1
        }
      }).then(res => {
        const allHouse = []
        this.columns = (res || []).map(item => {
          allHouse.push(this.getHouse(item.chick_column_id))
          item.enterHouses = []
          return item
        })
        Promise.all(allHouse).then(res => {
          if (this.columns.length !== res.length) { return }
          for (let i = 0; i < this.columns.length; i++) {
            this.columns[i].enterHouses = res[i]
          }
        })
      }).catch(err => {
        console.log(err)
      })
    },
    getHouse(columnId) {
      return new Promise((resolve, reject) => {
        this.$api.getData({
          server: 'agr_chain',
          table: 'chick_house_enter_view',
          params: {
            'chick_column_id.eq': columnId
          },
          order: {
            house_no: 'asc'
          }
        }).then(res => {
          resolve(res || [])
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 选择鸡舍，填写数量
    hideHousePopup() {
      this.$refs['housePopup'].hide()
      this.$tools.resignKeyboard()
    },
    houseBeforeClose() {
      this.houseVisible = false
    },
    selectHouseAmount(store) {
      this.selectStore = store

      // 根据选择的产品id过滤当前入栏和入舍信息
      const cs = []
      for (const column of this.columns) {
        // 过滤入库品类不一致的鸡舍
        if (column.output_product_category !== store.goods_category_id) {
          continue
        }

        const hs = []
        for (const house of column.enterHouses) {
          // 产品 <-> 库存 <-> 鸡苗 怎么对应？
          // if (house.product_id === store.goods_id) {
          const tempHouse = { ...house }
          const amount = undefined
          for (const st of store.extraInfo) {
            if (st.chick_house_enter_id === house.chick_house_enter_id) {
              amount = st.chick_amount
              break
            }
          }
          tempHouse.inputAmount = amount
          hs.push(tempHouse)
          // }
        }
        if (hs.length) {
          const temp = { ...column }
          temp.enterHouses = hs
          cs.push(temp)
        }
      }
      this.selectColumn = cs

      this.houseVisible = true
    },
    onHouseInputAmount(row) {
      const store = +row.current_amount || 0
      if (+row.inputAmount > store) {
        this.$notice.toast({ message: '存栏不足' })
        this.$set(row, 'inputAmount', store)
      }
    },
    onHouseSubmit() {
      const extraInfo = []
      let sum = 0
      for (const sc of this.selectColumn) {
        for (const h of sc.enterHouses) {
          if (h.inputAmount) {
            sum += +h.inputAmount || 0
            extraInfo.push({
              chick_house_enter_id: h.chick_house_enter_id,
              chick_amount: h.inputAmount,
              house_no: h.house_no,
              current_amount: h.current_amount
            })
          }
        }
      }
      this.selectStore.inputAmount = sum || ''
      this.selectStore.extraInfo = extraInfo
      this.hideHousePopup()
    },
    // 提交
    submit() {
      const masterData = {
        supplier_id: this.farm.id,
        supplier_name: this.farm.farmName,
        lister: this.user.userId,
        lister_name: this.user.realName || this.user.userName,
        // store_manager: this.servicer.res_person,
        // store_manager_name: this.servicer.res_person_name,
        accept_id: this.servicer.service_id,
        service_id: this.servicer.service_id,
        approval_status: '0'
      }

      const slaveData = []
      let i = 1
      for (const p of this.stores) {
        if (p.selected) {
          const sd = {
            order_num: i++,
            goods_id: p.goods_id,
            product_id: p.goods_id,
            product_category: p.goods_category_id,
            product_name: p.goods_name,
            remark: p.remark || '',
            ship_p_num: p.inputAmount,
            spec_id: p.spec_id,
            spec_name: p.spec_name,
            unit: p.spec_unit,
            unit_price: p.inputPrice,
            avg_weight: p.inputWeight,
            current_amount: 0
          }
          if (p.isChick) {
            sd.extra_info = []
            sd.current_amount = 0
            for (const ei of p.extraInfo) {
              sd.extra_info.push({
                chick_house_enter_id: ei.chick_house_enter_id,
                chick_amount: ei.chick_amount,
              })

              const ca = +ei.current_amount || 0
              sd.current_amount += ca
            }
          }
          slaveData.push(sd)
          const name = p.goods_name
          if (!p.inputWeight) {
            return this.$notice.toast({ message: `请填写 ${name} 的均重！` })
          }
          if (!p.inputPrice) {
            return this.$notice.toast({ message: `请填写 ${name} 的单价！` })
          }
          if (!p.inputAmount) {
            return this.$notice.toast({ message: `请填写 ${name} 的数量！` })
          }
        }
      }
      if (!slaveData.length) {
        return this.$notice.toast({ message: '至少添加一个农产品' })
      }

      const formData = {
        masterTableInfo: JSON.stringify(masterData),
        masterTableName: 'ship_p_form',
        slaveTableInfo: JSON.stringify(slaveData),
        slaveTableName: 'ship_p_form_detail'
      }

      this.$api.relatedBatch({
        server: 'agr_chain',
        data: formData,
        errorMsg: '提交失败，请重试'
      }).then(res => {
        this.$notice.toast({ message: '出库单添加成功' })
        this.$router.setBackParams({ type: 2 })
        this.$router.back()
      })
    }
  }
}
</script>
<style lang="scss" scoped>
@import "../../css/variables.scss";

.icon {
  font-family: alicon;
}
.p-1 {
  padding: 10px;
}
.p-2 {
  padding: 20px;
}
.p-3 {
  padding: 30px;
}
.pt-2 {
  padding: 20px;
}
.px-3 {
  padding-left: 30px;
  padding-right: 30px;
}
.pt-3 {
  padding-top: 30px;
}
.pb-1 {
  padding-bottom: 10px;
}
.pb-2 {
  padding-bottom: 20px;
}
.py-1 {
  padding-top: 10px;
  padding-bottom: 10px;
}
.bg-white {
  background-color: #fff;
}
.bg-light {
  background-color: $gray-100;
}
.mb-2 {
  margin-bottom: 20px;
}
.mb-1 {
  margin-bottom: 10px;
}
.mr-1 {
  margin-right: 10px;
}
.border-bottom {
  border-bottom-width: 1px;
  border-bottom-color: $border-color;
}
.text {
  font-size: 28px;
}
.text-sm {
  font-size: 26px;
}
.text-mini {
  font-size: 22px;
}
.text-muted {
  color: #999;
}
.text-primary {
  color: $primary;
}
.text-right {
  text-align: right;
}
.text-center {
  text-align: center;
}
.flex-row {
  flex-direction: row;
}
.flex {
  flex: 1;
}
.align-center {
  align-items: center;
}
.align-right {
  align-items: flex-end;
}

.flex-row-wp {
  flex-direction: row;
  background-color: #fff;
  padding-left: 30px;
  padding-right: 30px;
  padding-bottom: 10px;
}
.dt {
  width: 140px;
  font-size: 26px;
  color: #666;
}
.dd {
  flex: 1;
  font-size: 26px;
}

.list-row {
  padding-top: 20px;
  // padding-bottom: 20px;
  padding-right: 10px;
  background-color: #fff;
}

.input {
  flex: 1;
  border-width: 1px;
  border-color: $border-color;
  height: 60px;
  line-height: 60px;
  font-size: 26px;
  padding-left: 10px;
  padding-right: 10px;
  tint-color: #999;
}
.label-text {
  font-size: 26px;
  color: #666;
  margin-right: 10px;
}
.unit-text {
  font-size: 26px;
  background-color: $border-color;
  height: 60px;
  line-height: 60px;
  padding-left: 10px;
  padding-right: 10px;
  text-align: center;
  color: #666;
}
.textarea {
  font-size: 26px;
  color: #333;
  height: 300px;
  padding: 20px;
  border-width: 1px;
  border-color: $border-color;
  tint-color: #999;
}
.textarea-btn {
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.submit-wrap {
  background-color: #fff;
  border-top-width: 1px;
  border-top-color: $border-color;
  flex-direction: row;
  align-items: center;
}
.submit-num {
  flex: 1;
  font-size: 34px;
  color: $error;
  padding-left: 30px;
  padding-right: 30px;
}
.submit-btn {
  padding: 25px;
  color: #fff;
  font-size: 32px;
  background-color: $error;
}

.td-row {
  width: 750px;
  flex-direction: row;
  align-items: center;
  padding-top: 20px;
  padding-bottom: 20px;
  background-color: #fff;
  border-top-width: 1px;
  border-top-color: $border-color;
  border-bottom-width: 1px;
  border-bottom-color: $border-color;
}
.td-text {
  flex: 1;
  padding-left: 2px;
  padding-right: 2px;
  // text-align: center;
  font-size: 25px;
}
.td-serial {
  width: 40px;
  margin-left: 10px;
  font-size: 25px;
}
.td-select-icon {
  margin-top: 3px;
  font-size: 25px;
}

.dismiss-btn {
  width: 300px;
  height: 70px;
  line-height: 70px;
  border-radius: 35px;
  padding-left: 30px;
  padding-right: 30px;
  text-align: center;
  font-size: 28px;
  border-width: 1px;
  border-color: #ddd;
  margin-top: 20px;
  margin-bottom: 20px;
}
.dismiss-btn:active {
  background-color: #ddd;
}
.popup-btns {
  padding: 10px;
  border-top-width: 1px;
  border-top-color: #ddd;
}
.popup-btn-border {
  flex: 1;
  flex-direction: row;
  border-radius: 40px;
  border-width: 1px;
  border-color: $primary;
}
.popup-btn {
  flex: 1;
  padding: 16px;
  color: $primary;
}
.popup-btn-dismiss {
  border-top-left-radius: 40px;
  border-bottom-left-radius: 40px;
  background-color: lighten($primary, 45%);
}
.popup-btn-confirm {
  border-top-right-radius: 40px;
  border-bottom-right-radius: 40px;
  background-color: lighten($primary, 15%);
}
.popup-btn:active {
  background-color: lighten($primary, 35%);
}
.popup-btn-text {
  text-align: center;
}
</style>
